import axios from 'axios'
import store from '../store/'
import JSONbig from 'json-bigint'
import { Toast } from 'vant'
import router from '../router/index.js'

const refreshTokenReq = axios.create({
	baseURL:'http://ttapi.research.itcast.cn/'
})


const request = axios.create({
	baseURL:'http://ttapi.research.itcast.cn/',
	
	transformResponse: [function (data) {
		try {
			return JSONbig.parse(data)
		}catch (err) {
			
			return data
			
		}
	}]
})
//请求拦截器
request.interceptors.request.use(function(config) {
	const {user} = store.state
	if(user) {
		config.headers.Authorization = `Bearer ${user.token}`
	}
	return config;
},function(error) {
	return Promise.reject(error)
})

//响应拦截器
request.interceptors.response.use(function(response) {
	
	return response;
},async function(error) {
	const status = err.response.status
	if(status === 400) {
		//参数错误
		Toast.fail('客户端请求参数异常')
	}else if(status === 401) {
		//token无效
		if(!user || !user.state){
			return redirectLogin()
		}
		try {
			const { data } = await refreshTokenReq({
				method: 'PUT',
				url:'/app/v1_0/authorizations',
				headers: {
					Authorization:`Bearer ${user.refresh_token}`
				}
			})
			
			user.token = data.data.token
			store.commit('setUser',user)
			
			return request(error.config)
		}catch(err) {
			redirectLogin()
		}
		
	}else if(status === 403) {
		//权限问题
		Toast.fail('没有权限')
	}else if(status >= 500) {
		//服务端异常
		Toast.fail('服务端异常')
	}
	return Promise.reject(error)
})

function redirectLogin() {
	router.replace('/login')
}


export default request